<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>新建考试 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-danger {
        @apply bg-red-50 text-red-600 border border-red-200 px-3 py-1.5 rounded-lg transition-all duration-300 hover:bg-red-100 active:bg-red-200;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-bell-o"></i>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">张老师</span>
        </div>
      </div>
    </div>
  </header>

  <main class="flex-1 flex flex-col md:flex-row">
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            学生端
          </button>
        </div>
      </div>

      <nav id="teacher-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <nav id="student-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>

    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <div class="mb-6">
        <div class="flex items-center">
          <a href="/Publish_exam" class="text-gray-500 hover:text-primary mr-2">
            <i class="fa fa-arrow-left"></i>
          </a>
          <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">新建考试</h2>
        </div>
        <p class="text-gray-500 mt-1">填写考试信息，选择参与班级并设置考试时间</p>
      </div>

      <div class="bg-white rounded-xl p-6 card-shadow space-y-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">考试名称 <span class="text-red-500">*</span></label>
            <input id="exam-name" type="text" placeholder="输入考试名称"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">考试科目 <span class="text-red-500">*</span></label>
            <input id="exam-subject" type="text" placeholder="如：数学"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">授课教师 <span class="text-red-500">*</span></label>
            <input id="exam-teacher" type="text" placeholder="输入教师姓名"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">使用试卷 <span class="text-red-500">*</span></label>
            <input id="testpaper-name" type="text" placeholder="输入试卷名称"
                   value="{{ default_testpaper_name or '' }}"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-3">选择考试班级 <span class="text-red-500">*</span></label>
          {% if class_options %}
            <select id="exam-classes" multiple size="6"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              {% for class_name in class_options %}
                <option value="{{ class_name }}">{{ class_name }}</option>
              {% endfor %}
            </select>
            <p class="text-xs text-gray-500 mt-2">按住 Ctrl（或 Cmd）键可多选班级。</p>
          {% else %}
            <p class="text-gray-500 text-sm">暂无班级数据，请先在学生管理中添加班级信息。</p>
          {% endif %}
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">考试类型 <span class="text-red-500">*</span></label>
            <select id="exam-type" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option value="">请选择考试类型</option>
              <option value="周测">周测</option>
              <option value="月考">月考</option>
              <option value="期中考试">期中考试</option>
              <option value="期末考试">期末考试</option>
              <option value="模拟考试">模拟考试</option>
              <option value="自定义考试">每日考试</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">考试人数 <span class="text-red-500">*</span></label>
            <input id="exam-headcount" type="number" min="1" placeholder="输入参考人数"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">开始时间 <span class="text-red-500">*</span></label>
            <input id="exam-start-time" type="datetime-local"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">结束时间 <span class="text-red-500">*</span></label>
            <input id="exam-end-time" type="datetime-local"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">考试时长 (分钟) <span class="text-red-500">*</span></label>
          <input id="exam-duration" type="number" min="1" placeholder="例如：60"
                 class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
        </div>

        <div class="flex flex-col sm:flex-row justify-end gap-3 pt-4">
          <button class="btn-secondary px-6" id="cancel-btn">取消</button>
          <button class="btn-primary px-6" id="submit-btn">保存考试</button>
        </div>
      </div>
    </div>
  </main>

  <footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
      <p>2025 智慧教育考试系统 版权所有</p>
    </div>
  </footer>

  <script>
    const teacherTab = document.getElementById('teacher-tab');
    const studentTab = document.getElementById('student-tab');
    const teacherNav = document.getElementById('teacher-nav');
    const studentNav = document.getElementById('student-nav');

    teacherTab.addEventListener('click', () => {
      teacherNav.classList.remove('hidden');
      studentNav.classList.add('hidden');
    });


    const classSelect = document.getElementById('exam-classes');
    const submitBtn = document.getElementById('submit-btn');
    const cancelBtn = document.getElementById('cancel-btn');

    const tips = {
      examName: '考试名称不能为空',
      examSubject: '考试科目不能为空',
      examTeacher: '请选择授课教师',
      testpaperName: '请选择试卷',
      classIds: '请选择至少一个班级',
      examType: '请选择考试类型',
      headcount: '请填写考试人数（正整数）',
      startTime: '请选择考试开始时间',
      endTime: '请选择考试结束时间',
      duration: '请输入考试时长（分钟）',
      timeOrder: '结束时间必须晚于开始时间'
    };

    const showAlert = (message) => {
      alert(message);
    };

    cancelBtn.addEventListener('click', (event) => {
      event.preventDefault();
      window.location.href = '/Publish_exam';
    });

    const collectFormData = () => {
      const examName = document.getElementById('exam-name').value.trim();
      const examSubject = document.getElementById('exam-subject').value.trim();
      const examTeacher = document.getElementById('exam-teacher').value;
      const testpaperName = document.getElementById('testpaper-name').value;
      const classIds = classSelect
        ? Array.from(classSelect.selectedOptions).map((option) => option.value)
        : [];
      const examType = document.getElementById('exam-type').value;
      const headcount = document.getElementById('exam-headcount').value.trim();
      const startTime = document.getElementById('exam-start-time').value;
      const endTime = document.getElementById('exam-end-time').value;
      const duration = document.getElementById('exam-duration').value.trim();

      return {
        examName,
        examSubject,
        examTeacher,
        testpaperName,
        classIds,
        examType,
        headcount,
        startTime,
        endTime,
        duration
      };
    };

    const validateForm = (payload) => {
      if (!payload.examName) {
        showAlert(tips.examName);
        return false;
      }
      if (!payload.examSubject) {
        showAlert(tips.examSubject);
        return false;
      }
      if (!payload.examTeacher) {
        showAlert(tips.examTeacher);
        return false;
      }
      if (!payload.testpaperName) {
        showAlert(tips.testpaperName);
        return false;
      }
      if (!payload.classIds.length) {
        showAlert(tips.classIds);
        return false;
      }
      if (!payload.examType) {
        showAlert(tips.examType);
        return false;
      }
      if (!payload.headcount || Number.isNaN(Number(payload.headcount)) || Number(payload.headcount) <= 0) {
        showAlert(tips.headcount);
        return false;
      }
      if (!payload.startTime) {
        showAlert(tips.startTime);
        return false;
      }
      if (!payload.endTime) {
        showAlert(tips.endTime);
        return false;
      }
      if (!payload.duration || Number.isNaN(Number(payload.duration)) || Number(payload.duration) <= 0) {
        showAlert(tips.duration);
        return false;
      }

      const startDate = new Date(payload.startTime);
      const endDate = new Date(payload.endTime);
      if (endDate <= startDate) {
        showAlert(tips.timeOrder);
        return false;
      }

      return true;
    };

    const submitForm = async () => {
      const formData = collectFormData();
      if (!validateForm(formData)) {
        return;
      }

      submitBtn.disabled = true;
      submitBtn.textContent = '保存中...';

      try {
        const response = await fetch('/api/exam_schedules', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            exam_name: formData.examName,
            exam_subject: formData.examSubject,
            exam_teacher: formData.examTeacher,
            testpaper_name: formData.testpaperName,
            class_ids: formData.classIds,
            exam_type: formData.examType,
            headcount: Number(formData.headcount),
            start_time: formData.startTime,
            end_time: formData.endTime,
            duration_minutes: Number(formData.duration)
          })
        });

        if (!response.ok) {
          const errorData = await response.json().catch(() => ({ message: '创建考试失败' }));
          throw new Error(errorData.message || '创建考试失败');
        }

        showAlert('考试创建成功！');
        window.location.href = '/Publish_exam';
      } catch (error) {
        showAlert(error.message || '创建考试失败，请稍后重试');
      } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = '保存考试';
      }
    };

    submitBtn.addEventListener('click', (event) => {
      event.preventDefault();
      submitForm();
    });
  </script>
</body>
</html>
